package main

import (
	"fmt"
	"sync"
)

func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
	defer wg.Done()
	for j := range jobs {
		fmt.Printf("Worker %d processing job %d\n", id, j)
		results <- j * 2 // Example processing
	}
}

func main() {
	// 定义一个channel 用于接收错误
	codes := []string{"code1", "code2", "code3", "code1", "code2", "code3", "code1", "code2", "code3", "code1", "code2", "code3"}
	errchan := make(chan error, len(codes))
	sem := make(chan struct{}, 4) // 信号量，限制同时运行的 goroutine 数量为 10

	var wg sync.WaitGroup

	for _, code := range codes {
		wg.Add(1)
		sem <- struct{}{} // 向信号量发送信号
		go func(code string) {
			defer wg.Done()
			defer func() { <-sem }() // 从信号量中读取信号，释放一个位置

			var err error
			fmt.Println("============", code)
			err = fmt.Errorf("Error: %s", code) // 模拟错误
			// 使用 select 语句进行非阻塞发送
			select {
			case errchan <- err:
			default:
				fmt.Println("Error: channel is full")
			}
		}(code)
	}

	wg.Wait()
	close(errchan)

	for err := range errchan {
		if err != nil {
			fmt.Println("Error:", err)
			return
		}
	}
}
